package kr.hkit.summury_java.erp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import kr.hkit.myframework.db.DbUtil;
import kr.hkit.summury_java.erp.dto.CodeTitle;

public class CodeTitleDAO implements DaoInterface<CodeTitle>{
	private Connection connection;
	
	public CodeTitleDAO(Connection connection) {
		this.connection = connection;
	}

	@Override
	public void insertItem(CodeTitle item) throws SQLException {
		String sql = "insert into code_title values (?,?)";
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleno());
		pstmt.setString(2, item.getTitleName());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
	}

	@Override
	public void deleteItemByNo(CodeTitle item) throws SQLException {
		String sql = "delete from code_title where titleno = ?";
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleno());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
	}

	@Override
	public void updateItemByNo(CodeTitle item) throws SQLException {
		String sql = "update code_title set titlename = ? where titleno = ?";
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, item.getTitleName());
		pstmt.setInt(2, item.getTitleno());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
		
	}

	@Override
	public ArrayList<CodeTitle> listItems() throws SQLException {
		ArrayList<CodeTitle> list = new ArrayList<>();
		String sql = "select * from code_title";
		PreparedStatement pstmt = connection.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			list.add(new CodeTitle
					(rs.getInt("titleno"),
					 rs.getString("titleName")));
		}
		DbUtil.close(rs);
		DbUtil.close(pstmt);
		return list;
	}

	@Override
	public CodeTitle searchItem(CodeTitle item) throws SQLException {
		CodeTitle codetitle = null;
		String sql = "select titleno, titlename from code_title where titleno=?";
		PreparedStatement pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleno());
		ResultSet rs = pstmt.executeQuery();
		
		if (rs.next()) {
			codetitle = new CodeTitle();
			codetitle.setTitleno(rs.getInt(1));
			codetitle.setTitleName(rs.getString(2));
		}
		
		return codetitle;
	}

	

}
